package com.shujia.wyh.utils;

import java.io.BufferedReader;
import java.io.FileReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.Statement;
import java.util.Properties;

public class MySqlTool {
    private static Statement statement;
    private static PreparedStatement preparedStatement;
    private static Connection conn;

    //构造方法私有化
    private MySqlTool(){}

    public static Connection getConnection(){
        return conn;
    }

    /**
     * 编写获取数据库操作对象的方法
     */
    public static PreparedStatement getStatement(String sql) {
        try {

            //读取配置文件
            Properties properties = new Properties();
            properties.load(new BufferedReader(new FileReader("redis/src/main/java/com/shujia/wyh/utils/mysql.properties")));
            //获取数据库的驱动包位置
            String dbVersion = properties.getProperty("dbVersion");
            //获取数据库的连接
            String url = properties.getProperty("url");
            //获取登录数据库的用户名
            String user = properties.getProperty("user");
            //获取登录数据库的密码
            String password = properties.getProperty("password");


            Class.forName(dbVersion);

            conn = DriverManager.getConnection(url, user, password);


            //获取操作数据库的对象
//            statement = conn.createStatement();
            //创建一个预防sql注入的数据库操作对象
            //先解析sql
            preparedStatement = conn.prepareStatement(sql);

        } catch (Exception e) {
            e.printStackTrace();
        }

        return preparedStatement;
    }

    public static Statement getStatement() {
        try {

            //读取配置文件
            Properties properties = new Properties();
            properties.load(new BufferedReader(new FileReader("redis/src/main/java/com/shujia/wyh/utils/mysql.properties")));
            //获取数据库的驱动包位置
            String dbVersion = properties.getProperty("dbVersion");
            //获取数据库的连接
            String url = properties.getProperty("url");
            //获取登录数据库的用户名
            String user = properties.getProperty("user");
            //获取登录数据库的密码
            String password = properties.getProperty("password");


            Class.forName(dbVersion);

            conn = DriverManager.getConnection(url, user, password);


            //获取操作数据库的对象
            statement = conn.createStatement();

        } catch (Exception e) {
            e.printStackTrace();
        }

        return statement;
    }
}
